<template>
  <!-- ref获取DOM元素 -->
  <div class="swiper" ref="swiper">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="banner in bannerList" :key="banner.id">
        <img :src="banner.imgUrl" :alt="`banner${banner.id}`" />
      </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>
    <!-- 如果需要导航按钮 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
import Swiper from 'swiper/bundle'
import 'swiper/css/bundle'
export default {
  name: 'XCarousel',
  props: {
    bannerList: Array,
  },
  // mounted(){},
  watch: {
    bannerList: {
      async handler(newVal) {
        if (!newVal.length) return
        // 等bannerList有数据时触发
        // console.log(newVal)
        // vue所有更新都是异步的
        // bannerList有值,但是还未渲染成DOM元素
        await this.$nextTick() //等DOM元素更新好

        new Swiper(this.$refs.swiper, {
          autoplay: true, // 自动轮播
          // autoplay: {
          //   delay: 1000,
          // },
          loop: true, // 无限轮播
          // 小圆点
          pagination: {
            el: '.swiper-pagination',
            clickable: true, // 可以点击跳转
          },
          // 左右箭头
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          },
        })
      },
      immediate: true, //让监视属性第一次触发
    },
  },
}
</script>

<style lang="less" scoped></style>
